﻿using System.Net.NetworkInformation;

namespace TcpService
{
    public static class PingChecker
    {
        public static async Task<bool> ContinuousPing(string ip, TimeSpan timeout, CancellationToken ct = default(CancellationToken))
        {
            // 创建 Ping 实例
            using var pingSender = new Ping();

            // 记录开始时间
            DateTime startTime = DateTime.Now;

            // 循环检测直到超时
            while (DateTime.Now - startTime < timeout)
            {
                try
                {
                    // 发送 Ping 请求（设置单次超时为 1000ms）
                    Task<PingReply> task = pingSender.SendPingAsync(ip, 100);
                    await task;
                    ct.ThrowIfCancellationRequested();
                    // 检测是否连通
                    if (task.Result.Status == IPStatus.Success)
                    {
                        return true;
                    }
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (PingException)
                {
                    // 忽略单次失败，继续重试
                }

                // 等待 200ms 后重试，避免高频请求
                Thread.Sleep(200);
            }
            return false; // 超时未连通
        }
    }
}